package com.cooode.web.controller;

import com.cooode.common.constant.Constants;
import com.cooode.common.uitls.ServletUtils;
import com.cooode.framework.service.SysLoginService;
import com.cooode.framework.service.TokenService;
import com.cooode.framework.vo.LoginUser;
import com.cooode.framework.web.controller.BaseController;
import com.cooode.framework.web.entity.ResultData;
import com.cooode.web.entity.SysMenu;
import com.cooode.web.entity.SysUser;
import com.cooode.web.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;

/**
 * @desc 登录验证
 * @author tianmaochang
 */
@RestController
public class SysLoginController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 登录方法
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    @PostMapping("/login")
    public ResultData login(String username, String password, String code, String uuid) {
        ResultData resultData = ResultData.success();
        // 生成令牌
        String token = loginService.login(username, password, code, uuid);
        resultData.put(Constants.TOKEN, token);
        return resultData;
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    @GetMapping("getUserInfo")
    public ResultData getInfo() {
        // 获得当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        ResultData resultData = ResultData.success();
        resultData.put("user", user);
        resultData.put("roles", new HashSet<>());
        resultData.put("permissions", new HashSet<>());
        return resultData;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getMenus")
    public ResultData getMenus() {
        // 获得当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return ResultData.success(menuService.buildMenus(menus));
    }
}
